package com.yuuko.yuukoapi.framework.interceptor

import com.yuuko.yuukoapi.model.base.BaseEntity
import com.yuuko.yuukoapi.model.base.BaseEntityDraft
import org.babyfish.jimmer.kt.isLoaded
import org.babyfish.jimmer.sql.DraftInterceptor
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class EntityDraftInterceptor : DraftInterceptor<BaseEntity, BaseEntityDraft> {
    override fun beforeSave(draft: BaseEntityDraft, original: BaseEntity?) {
        // 创建对象时
        if (original == null) {
            if (!isLoaded(draft, BaseEntityDraft::createdAt)) {
                draft.createdAt = LocalDateTime.now()
            }
            if (!isLoaded(draft, BaseEntityDraft::updatedAt)) {
                draft.updatedAt = LocalDateTime.now()
            }
        } else {
            if (!isLoaded(draft, BaseEntityDraft::updatedAt)) {
                draft.updatedAt = LocalDateTime.now()
            }
        }
    }
}